package com.train.mgr.modules.biz.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class Mp4ToWma {

    /** 把 mp4 中的音频转码为 wma/wmv（asf 容器） */
    public static boolean mp4ToWma(File mp4, File wma) {
        // 1. 构造命令：只取音频、转码器选 wmav2、采样率 44.1 k、双声道
        String[] cmd = {
                "ffmpeg",
                "-y",                       // 覆盖输出
                "-i", mp4.getAbsolutePath(),
                "-vn",                      // 不要视频
                "-acodec", "wmav2",         // 微软 wma2 编码器
                "-ar", "44100",
                "-ac", "2",
                "-b:a", "128k",             // 码率 128 kbps
                wma.getAbsolutePath()
        };

        // 2. 执行
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);   // 合并 stderr 到 stdout
        try {
            Process proc = pb.start();
            // 3. 消费输出，避免阻塞
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(proc.getInputStream()))) {
                String line;
                while ((line = br.readLine()) != null) {
                    // 如需日志可写文件
                    System.out.println(line);
                }
            }
            int exit = proc.waitFor();
            return exit == 0;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

//    /**
//     * 把 mp4 中的音频提取成 wav（PCM 16bit 44.1kHz 双声道）
//     * @param mp4 输入文件
//     * @param wav 输出文件
//     * @return 成功 true
//     */
//    public static boolean convert(File mp4, File wav) {
//        // 1. 构造命令
//        String[] cmd = {
//                "ffmpeg",
//                "-y",                   // 覆盖输出
//                "-i", mp4.getAbsolutePath(),
//                "-vn",                  // 丢弃视频
//                "-acodec", "pcm_s16le", // PCM 16bit 小端
//                "-ar", "44100",
//                "-ac", "2",
//                wav.getAbsolutePath()
//        };
//
//        // 2. 执行
//        ProcessBuilder pb = new ProcessBuilder(cmd);
//        pb.redirectErrorStream(true);          // 合并 stderr→stdout
//        try {
//            Process proc = pb.start();
//            // 3. 消费输出，防止缓冲区打满
//            try (BufferedReader br = new BufferedReader(
//                    new InputStreamReader(proc.getInputStream()))) {
//                String line;
//                while ((line = br.readLine()) != null) {
//                    // 如需静默可删除下面打印
//                    System.out.println(line);
//                }
//            }
//            return proc.waitFor() == 0;
//        } catch (IOException | InterruptedException e) {
//            e.printStackTrace();
//            return false;
//        }
//    }

    /** 探测音频流：返回 {sampleRate, channels} */
    private static int[] probeAudio(File mp4) throws IOException {
        String[] cmd = {
                "ffprobe", "-v", "error", "-select_streams", "a:0",
                "-show_entries", "stream=sample_rate,channels",
                "-of", "csv=p=0", mp4.getAbsolutePath()
        };
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Process p = pb.start();
        String line;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            line = br.readLine();          // 44100,2
        }
        String[] sp = line.trim().split(",");
        int sr = Integer.parseInt(sp[0]);
        int ch = Integer.parseInt(sp[1]);
        return new int[]{sr, ch};
    }

    /** 根据实际属性决定目标参数 */
    private static int decideTargetRate(int originalRate) {
        return originalRate >= 16000 ? 16000 : 8000;
    }

    /** 真正转码 */
    public static boolean convert(File mp4, File wav) throws IOException {
        int[] info = probeAudio(mp4);
        int srcRate = info[0];
        int srcCh   = info[1];
        int tgtRate = decideTargetRate(srcRate);

        String[] cmd = {
                "ffmpeg", "-y",
                "-i", mp4.getAbsolutePath(),
                "-vn",                          // 无视频
                "-acodec", "pcm_s16le",         // 16 bit PCM
                "-ar", String.valueOf(tgtRate), // 16k 或 8k
                "-ac", "1",                     // 强制单声道
                wav.getAbsolutePath()
        };

        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Process p = pb.start();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String l;
            while ((l = br.readLine()) != null) { /* 可静默 */ }
        }
        try {
            return p.waitFor() == 0;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }


    // ---------------------- 测试 ----------------------
    public static void main(String[] args) throws IOException{
        File in = new File("/Users/tianyi/Documents/logo/aaaa.mp4");
        File out = new File("/Users/tianyi/Documents/logo/aaaa.wav");
        long start = System.currentTimeMillis();

       // boolean ok = mp4ToWma(in, out);

        boolean ok = convert(in, out);
        long cost = System.currentTimeMillis() - start;
        System.out.println(ok ? "转码成功" : "转码失败");
        System.out.printf("耗时: %.2f s%n", cost / 1000.0);
    }
}
